﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;

namespace PortDetection
{
    public class SendMail
    {
        MailMessage mailMessage;

        SmtpClient smtpClient;

        string password;

        #region 发送1
        /// <summary>
        /// 
        /// </summary>
        /// <param name="to">收件人</param>
        /// <param name="from">发件人</param>
        /// <param name="title">标题</param>
        /// <param name="body">内容</param>
        /// <param name="password">授权码</param>
        public SendMail(string to,string from,string title,string body,string password)
        {
            mailMessage = new MailMessage();
            mailMessage.To.Add(to);        //收件人
            mailMessage.From = new System.Net.Mail.MailAddress(from); // 发件人
            mailMessage.Subject = title;    //邮件标题
            mailMessage.Body = body;        //邮件内容
            mailMessage.IsBodyHtml = true;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;    //正文的编码
            mailMessage.Priority = System.Net.Mail.MailPriority.High;   //邮件优先级
            mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
            mailMessage.CC.Add(to);
            this.password = password;
        }

        /// <summary>
        /// 添加附件，保留
        /// </summary>
        /// <param name="attachmentsPath">附件路径；号隔开</param>
        public void Attachments(string attachmentsPath)
        {
            try
            {
                string[] path = attachmentsPath.Split(';');
                Attachment data;
                ContentDisposition disposition;
                for (int i = 0; i < path.Length;i++ )
                {
                    data = new Attachment(path[i], MediaTypeNames.Application.Octet);
                    disposition = data.ContentDisposition;
                    disposition.CreationDate = File.GetCreationTime(path[i]);
                    disposition.ModificationDate = File.GetLastWriteTime(path[i]);
                    disposition.ReadDate = File.GetLastAccessTime(path[i]);
                    mailMessage.Attachments.Add(data);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        public bool Send()
        {
            if (mailMessage != null)
            {
                try
                {
                    ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
                    smtpClient = new SmtpClient();
                    smtpClient.EnableSsl = true;
                    smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, this.password);
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host = "smtp." + mailMessage.From.Host;
                    smtpClient.Send(mailMessage);
                    return true;
                }
                catch (Exception ex)    
                {
                    WriteLog.DataLog(ex);
                    return false;
                }
                
            }
            return false;
        }
        #endregion
        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            //为了通过证书验证，总是返回true
            return true;
        }
        #region  方法2
        /// <summary>
        /// 发送邮件（发送方一定要在邮箱中添加stmp服务）
        /// </summary>
        /// <param name="toMail">接受方</param>
        /// <param name="fromMail">发送方</param>
        /// <param name="title">邮件标题</param>
        /// <param name="body">邮件内容</param>
        /// <param name="password">密码（QQ邮箱使的是授权码）</param> 
        public static void sendMail(string toMail,string fromMail,string title,string body,string password)
        {
            MailMessage sendmail=new MailMessage ();
            #region  邮件赋值
            sendmail.To.Add(toMail); //接受方地址
            sendmail.From=new MailAddress(fromMail);  //发送方地址
            sendmail.Subject=title;   //邮件标题行
            sendmail.IsBodyHtml=true;
            sendmail.Body=body;       //邮件内容
            sendmail.BodyEncoding=System.Text.Encoding.UTF8;  //编码格式
            sendmail.DeliveryNotificationOptions=DeliveryNotificationOptions.OnSuccess;
            #endregion

            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
            SmtpClient sClient=new SmtpClient ();//发送协议设置
            NetworkCredential nc=new NetworkCredential (); //发件人邮箱密码
            nc.UserName=fromMail;    //账号
            nc.Password=password;    //密码

            sClient.EnableSsl=true;   //使用套接字加密 （QQ邮箱一定要添加，其他邮箱没有）
            sClient.UseDefaultCredentials = true;
            sClient.DeliveryMethod=SmtpDeliveryMethod.Network;
            sClient.Credentials=nc;
            sClient.Host = "smtp." + sendmail.From.Host; ;//发送方的服务器
            sClient.Send(sendmail);
        }

        #endregion



        public static void SendMail2(string to, string from, string title, string body, string password)
        {
            try
            {
                MailMessage mm = new MailMessage();
                MailAddress fromMa = new MailAddress(from);
                MailAddress toMa = new MailAddress(to, null);
                mm.From = fromMa;
                //收件人
                mm.To.Add(to);
                //邮箱标题
                mm.Subject = title;
                mm.IsBodyHtml = true;
                //邮件内容
                mm.Body = body;
                //内容的编码格式
                mm.BodyEncoding = System.Text.Encoding.UTF8;
                //mm.ReplyTo = Toma;
                //mm.Sender =Fromma;
                //mm.IsBodyHtml = false;
                mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
                mm.CC.Add(toMa);

                ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
                SmtpClient sc = new SmtpClient();
                NetworkCredential nc = new NetworkCredential();
                nc.UserName = from;//你的邮箱地址
                nc.Password = password;//你的邮箱密码,这里的密码是xxxxx@qq.com邮箱的密码，特别说明下~
                sc.EnableSsl = true;//(一定要加)
                sc.UseDefaultCredentials = true;
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;
                sc.Credentials = nc;
                //如果这里报mail from address must be same as authorization user这个错误，是你的QQ邮箱没有开启SMTP，
                //到你自己的邮箱设置一下就可以啦！在帐户下面,如果是163邮箱的话，下面该成smtp.163.com
                //sc.Host = "smtp.qq.com";
                sc.Host = "smtp." + from.Split('@')[1];
                sc.Send(mm);

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
